import type { UnwrapNestedRefs } from 'vue';
import { store } from '@store';
import { getUserInfo } from '@api';
import { MenuRoute } from '@/types/interface';

/**
 * 用户信息
 */
interface UserState {
  userInfo: {
    /** 用户Id */
    userId?: string;
    /** 用户名 */
    username?: string;
    /** 昵称 */
    nickname?: string;
    /** 头像 */
    avatar?: string;
  };
  /** 菜单 */
  menus: MenuRoute[];
  /** 权限 */
  permissions: string[];
  /** 登录信息 */
  loginInfo: {
    /** 登录状态 */
    status: boolean;
    /** 登录token */
    token: string;
    /** 过期时间 */
    expireTime: number;
  };
}

interface UserStore {
  userState: UnwrapNestedRefs<UserState>;
  updateState: (payload: Partial<UserState>) => void;
  initUserInfo: () => Promise<void>;
  resetState: () => Promise<void>;
}

export const useUserStore = defineStore<string, UserStore>(
  'user',
  () => {
    const userState = reactive<UserState>({
      userInfo: {
        /** 用户Id */
        userId: 'assss111',
        /** 用户名 */
        username: 'admin',
        /** 昵称 */
        nickname: '管理员',
        /** 头像 */
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
      },
      menus: [],
      permissions: [],
      loginInfo: {
        status: true,
        token: 'asdasdd',
        expireTime: 0,
      },
    });

    /** 更新 */
    const updateState = (payload: Partial<UserState>) => {
      for (let key in payload) {
        if (key in userState) {
          const value = payload[key as keyof UserState];
          if (value) {
            toRef(userState, key as keyof UserState).value = value;
          }
        }
      }
    };

    /** 初始化用户信息 */
    const initUserInfo = () =>
      getUserInfo().then((res) => {
        updateState({
          userInfo: {
            userId: res.userInfo.userId,
            username: res.userInfo.username,
            nickname: res.userInfo.nickname,
            avatar: res.userInfo.avatar,
          },
          menus: res.menus,
          permissions: res.permissions,
        });
      });

    // const initRoutes = () => {
    //   const menus = [];
    //   const permissions = [];
    // };

    /** 退出 */
    const resetState = () =>
      new Promise<void>((resolve) => {
        updateState({
          userInfo: {
            userId: '',
            username: '',
            nickname: '',
            avatar: '',
          },
          menus: [],
          permissions: [],
          loginInfo: {
            status: false,
            token: '',
            expireTime: 0,
          },
        });
        setTimeout(() => {
          resolve();
        }, 3000);
        // resolve();
      });

    return {
      userState,
      updateState,
      initUserInfo,
      resetState,
    };
  },
  {
    persist: [
      {
        afterRestore: (payload) => {
          console.log('前置 payload', payload);
        },
        storage: window.sessionStorage,
        paths: ['userState'],
      },
    ],
  },
);

export function getUseUserStore() {
  return useUserStore(store);
}
